package com.example.dangerouscargodriver.ui.activity;

import androidx.appcompat.app.AlertDialog;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.controller.AreaInfoController;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.BankAccountInfoController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.IControllerEventListener;
import com.example.dangerouscargodriver.entry.BankAccount;
import com.example.dangerouscargodriver.entry.EmployeeInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

public class UserCardActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "UserCardActivity";
    private static final int MSG_REFRESH_BANK_ACCOUNT_LOADED = 0;
    private static final int MSG_GET_CHILD_ACCOUNT = 1;

    private MyHandler mHandler = null;
    private MyControllerEventListener mControllerListener = null;


    private ActionBar mActionBar = null;
    private LinearLayout mBindingCard = null;
    private LinearLayout mEmptyCardLayout = null;
    private LinearLayout mCardInfoLayout = null;
    private AlertDialog mDialog = null;
    private Button mUnBindCard = null;
    private Button mChangeCard = null;

    private TextView mBankType = null;
    private TextView mCardStatus = null;
    private TextView mCardType = null;
    private TextView mCardNo = null;

    private BankAccount mBankAccount = null;

    private boolean mIsCreate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(UserCardActivity.class);
        setContentView(R.layout.activity_user_card);

        mEmptyCardLayout = findViewById(R.id.layout_empty_card);
        mCardInfoLayout = findViewById(R.id.layout_has_card);
        mBindingCard = findViewById(R.id.layout_add_card);
        mBindingCard.setOnClickListener(this);

        mUnBindCard = findViewById(R.id.btn_unbind_card_info);
        mUnBindCard.setOnClickListener(this);
        mChangeCard = findViewById(R.id.btn_change_card_info);
        mChangeCard.setOnClickListener(this);

        mBankType = findViewById(R.id.tv_card_bank_type);
        mCardStatus = findViewById(R.id.tv_card_status);
        mCardType = findViewById(R.id.tv_card_type);
        mCardNo = findViewById(R.id.tv_card_no);

        init();

        mActionBar = findViewById(R.id.actionBarUserCard);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        BankAccountInfoController.Instance().attachControllerListener(
                UserCardActivity.class,
                mControllerListener);
    }

    private  void init() {
        mHandler = new MyHandler(this);
        mControllerListener = new MyControllerEventListener();
    }

    private void requestBankAccountInfo(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        sendHttpRequest(
                IHttpRequest.RequestMethod.GET_METHOD,
                RemoteAPI.REQUEST_V1_USER_BANK_ACCOUNT,
                header,
                null,
                RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT);
    }

    private void addEmptyCardLayoutView(){
        mCardInfoLayout.setVisibility(View.GONE);
        mEmptyCardLayout.setVisibility(View.VISIBLE);
    }

    private void addCardInfoLayoutView(){
        mCardInfoLayout.setVisibility(View.VISIBLE);
        mEmptyCardLayout.setVisibility(View.GONE);
    }

    private void refreshCardInfoView(){
        mBankType.setText(mBankAccount.getBank_name());
        mCardType.setText(mBankAccount.getBank_desc());
        mCardNo.setText(mBankAccount.getCard_num());
        if(mBankAccount.getBind_status().equals("1")){
            mCardStatus.setText("(待审核)");
        }
        else if(mBankAccount.getBind_status().equals("2")){
            mCardStatus.setText("(审核拒绝)");
        }
        else{
            mCardStatus.setText("(审核通过)");
        }
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    mBankAccount = gson.fromJson(res.getString("data"), BankAccount.class);
                    addCardInfoLayoutView();
                    refreshCardInfoView();
                }
                if(responseInfo != null && responseInfo.getStatus() == 0){
                    //用户未绑定银行卡
                    addEmptyCardLayoutView();
                }
            }
            if(actionId == RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT_DELETE){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                ToastUtils.showLongToast(this, res.getString("message"));
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    BankAccountInfoController.Instance().updateBindingInfo();
                }
                else{
                    /**/
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT){
            ToastUtils.showLongToast(this, "请求失败，请稍后重试!");
        }
        else if(actionId == RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT_DELETE){
            ToastUtils.showLongToast(this, "请求失败，请稍后重试!");
        }
        else if(actionId == RemoteAPICmd.REQUEST_V1_CHILD_ACCOUNT){
            /**/
        }
    }

    private void showAlertDialog() {
        View view = LayoutInflater.from(this).inflate(
                R.layout.layout_choose_band_card_type_alert_dialog, null);

        TextView positiveButton = view.findViewById(R.id.alert_dialog_positive_text);
        TextView negativeButton = view.findViewById(R.id.alert_dialog_negative_text);
        CheckBox mOfficial = view.findViewById(R.id.ck_item_card_official);
        CheckBox mPersonal = view.findViewById(R.id.ck_item_card_personal);

        positiveButton.setOnClickListener(v -> {
            if(mOfficial.isChecked()){
                Intent intent = new Intent(this, BindingOfficialCardActivity.class);
                startActivity(intent);
            }
            if(mPersonal.isChecked()){
                Intent intent = new Intent(this, BindingPersonalCardActivity.class);
                startActivity(intent);
            }
            mDialog.dismiss();
        });
        negativeButton.setOnClickListener(v -> {

            mDialog.dismiss();
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);

        builder.setCancelable(true);   //返回键dismiss
        //创建对话框
        mDialog = builder.create();
        mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);//去掉圆角背景背后的棱角
        mDialog.setCanceledOnTouchOutside(true);   //失去焦点dismiss
        mDialog.show();
    }

    private void executeUnBindCard(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        if(mBankAccount != null) {
            sendHttpRequest(
                    IHttpRequest.RequestMethod.DELETE_METHOD,
                    RemoteAPI.REQUEST_V1_USER_BANK_ACCOUNT + "/" + mBankAccount.getId(),
                    header,
                    null,
                    RemoteAPICmd.REQUEST_V1_USER_BANK_ACCOUNT_DELETE);
        }
    }

    private void refreshViewInfo() {
        if(BankAccountInfoController.Instance().getCardBindStatus() ==
                BankAccountInfoController.BANK_BIND_STATUS_DONE){
            addCardInfoLayoutView();
            mBankAccount = BankAccountInfoController.Instance().getBankCardInfo();
            refreshCardInfoView();
        }
        else{
            addEmptyCardLayoutView();
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.layout_add_card){
            showAlertDialog();
        }
        else if(v.getId() == R.id.btn_unbind_card_info){
            executeUnBindCard();
        }
        else if(v.getId() == R.id.btn_change_card_info){
            Intent intent = new Intent(this, ChangeCardInfoActivity.class);
            startActivity(intent);
        }
        else{

        }
    }

    @Override
    public void onResume(){
        super.onResume();
        if(mIsCreate){
            mIsCreate = false;
        }
        else{
            refreshViewInfo();
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        BankAccountInfoController.Instance().unAttachControllerListener(UserCardActivity.class,
                mControllerListener);
    }

    private class MyHandler extends Handler {
        WeakReference<UserCardActivity> mActivity;

        MyHandler(UserCardActivity activity) {
            mActivity = new WeakReference<UserCardActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            UserCardActivity activity = mActivity.get();
            switch (msg.what){
                case MSG_REFRESH_BANK_ACCOUNT_LOADED:
                    refreshViewInfo();
                    break;
                default:
                    break;
            }
        }
    }

    private class MyControllerEventListener implements IControllerEventListener {

        @Override
        public void onEvent(int eventId, String json) {
            if(eventId == Event.EVENT_LOAD_HTTP_BANK_ACCOUNT){
                Gson gson = new Gson();
                LoadHttpResourceStatus status = gson.fromJson(json, LoadHttpResourceStatus.class);
                Log.d(TAG, "onEvent: " + status.toJson());
                if(status.getWhat() == AreaInfoController.EVENT_AREA_LOAD_DONE){
                    Message msg = new Message();
                    msg.what = MSG_REFRESH_BANK_ACCOUNT_LOADED;
                    mHandler.sendMessage(msg);
                }
            }
        }
    }
}